<template>
    <div>
        <iframe ref="iframeRef" :src="url" width="500" height="400" @load="onIframeLoad"
        style="border:none;background-color: yellowgreen;" name="demo" id="myFrame"></iframe>
        <button @click="sendMessage">发送消息</button>
    </div>
</template>
<script setup lang='ts'>
import { ref,reactive,onMounted, onUnmounted } from 'vue'
const url = ref('http://192.168.6.124:8082') // iframe地址
const iframeRef = ref(null)


onMounted(() => {})

onUnmounted(() => {
    console.log('父页面iframe页面卸载了')
    window.removeEventListener('message', sendMessage);
})
// 父页面代码： 主要用window.addEventListener监听消息用postMessage发送消息。
const sendMessage = () => {
    const iframe = iframeRef.value;
    if (iframe.contentWindow) {
        // 使用 window.postMessage 实现跨域通信
        iframe.contentWindow.postMessage('Hello!', '*');
    }
}
</script>

<style scoped lang='scss'>
</style>